package covertjava.decompile;

/**
 * <p>Extended version of MessageInfo with a complex implementation of message
 * id generation and an inner class.</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class MessageInfoComplex implements java.io.Serializable {

    String hostName;
    String userName;

    public MessageInfoComplex(String hostName, String userName) {
        this.hostName = hostName;
        this.userName = userName;
    }

    /**
     * @return name of the host that sent the message
     */
    public String getHostName() {
        return hostName;
    }

    /**
     * @return name of the user that sent the message
     */
    public String getUserName() {
        return userName;
    }


    /**
     * Convenience method to obtain a string that best identifies the user.
     * @return name that should be used to identify a user that sent this message
     */
    public String getDisplayName() {
        return getUserName() + " (" + getHostName() + ")";
    }


    /**
     * Generate message id that can be used to identify this message in a database
     * The format is: <ID><UserName><HostName>. Names are limited to 8 characters
     * Example: 443651_Kalinovs_JAMAICA would be generated for Kalinovsky/JAMAICA
     */
    public String generateMessageId() {
        StringBuffer id = new StringBuffer(22);

        String systemTime = "" + System.currentTimeMillis();
        id.append(systemTime.substring(0, 6));

        if (getUserName() != null && getUserName().length() > 0) {
            // Add user name if specified
            id.append('_');
            int maxChars = Math.min(getUserName().length(), 8);
            id.append(getUserName().substring(0, maxChars));
        }

        if (getHostName() != null && getHostName().length() > 0) {
            // Add host name if specified
            id.append('_');
            int maxChars = Math.min(getHostName().length(), 7);
            id.append(getHostName().substring(0, maxChars));
        }
        return id.toString();
    }


    /**
     * Include an example of anonymous inner class
     */
    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                System.out.println("Running test");
                MessageInfoComplex info = new MessageInfoComplex("JAMAICA", "Kalinovsky");
                System.out.println("Message id = " + info.generateMessageId());
                info = new MessageInfoComplex(null, "JAMAICA");
                System.out.println("Message id = " + info.generateMessageId());
            }
        }).start();
    }


    /**
     * Inner class that can be used as a primary key for MessageInfoComplex
     */
    public static class MessageInfoPK implements java.io.Serializable {
        public String id;
    }

}
